from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from untils.tencents import cos
from web.forms.wiki import WikiModelForm
from web import models
import uuid


def wiki(request, project_id):
    '''wiki首页'''
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    '''wiki添加'''
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_form.html', {'form': form})

    # POST
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        form.instance.project = request.tracer.project
        form.save()

        url = reverse('wiki', kwargs={'project_id': project_id})

        return redirect(url)

    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    '''文档列表显示'''
    wiki_data = models.Wiki.objects.filter(project=request.tracer.project).order_by('depth', 'id').values('id', 'title',
                                                                                                          'parent_id')

    if wiki_data:
        return JsonResponse({'status': True, 'data': list(wiki_data)})

    return JsonResponse({'status': False})


def wiki_delete(request, project_id, wiki_id):
    '''删除文档'''
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()

    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    '''编辑文档'''
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})

    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        form.instance.project = request.tracer.project
        form.save()

    url = reverse('wiki', kwargs={'project_id': project_id})
    preview_url = f"{url}?wiki_id={wiki_id}"
    return redirect(preview_url)


@csrf_exempt
def wiki_upload(request, project_id):
    """markdown插件上传图片"""

    # 上传成功后markdown需要返回的参数
    result = {
        'success': 0,  # 0 表示失败，1表示成功
        'message': None,  # 返回消息
        'url': None  # 返回的地址
    }

    print(request.FILES)
    image_object = request.FILES.get('editormd-image-file')

    if not image_object:
        result['message'] = '文件不存在'
        return JsonResponse(result)

    # 调用方法上传图片对象到cos
    bucket = request.tracer.project.bucket
    region = request.tracer.project.region

    # 对图片的名字进行按.切割成列表然后取最后一个值（其实就是取图片的后缀名）
    ext = image_object.name.rsplit('.')[-1]
    key = f"{request.tracer.user.mobile_phone}-{str(uuid.uuid4())}.{ext}"
    # 上传图片并拿到返回值
    image_url = cos.upload_file(bucket, region, image_object, key)
    result['success'] = 1
    result['url'] = image_url
    print(result)

    return JsonResponse(result)
